/**
 * @author chuzhixin 1204505056@qq.com （不想保留author可删除）
 * @description 路由守卫，目前两种模式：all模式与intelligence模式
 */
import router from '@/router'
import store from '@/store'
import VabProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/pageTitle'
import checkPermission from '@/utils/permission'
import {
  authentication,
  loginInterception,
  progressBar,
  recordRoute,
  routesWhiteList,
  routesGuardWhiteList,
} from '@/config'

VabProgress.configure({
  easing: 'ease',
  speed: 500,
  trickleSpeed: 200,
  showSpinner: false,
})
router.beforeResolve(async (to, from, next) => {
  if (progressBar) VabProgress.start()
  let hasToken = store.getters['user/accessToken']
  // if (!loginInterception) hasToken = true
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      if (progressBar) VabProgress.done()
    } else {
      const hasPermissions =
        store.getters['user/permissions'] &&
        store.getters['user/permissions'].length > 0
      if (hasPermissions) {
        next()
      } else {
        // console.log('走设置路由')
        try {
          let permissions
          if (!loginInterception) {
            //settings.js loginInterception为false时，创建虚拟权限
            await store.dispatch('user/setPermissions', ['adminFaker'])
            permissions = ['adminFaker']
          } else {
            permissions = await store.dispatch('user/getUserInfo')
          }
          // 此处设置左侧路由，将功能修改到点击顶部一级菜单后获取！
          // let accessRoutes = []
          // if (authentication === 'intelligence') {
          //   accessRoutes = await store.dispatch('routes/setRoutes', permissions)
          // } else if (authentication === 'all') {
          //   accessRoutes = await store.dispatch('routes/setAllRoutes')
          // }
          // accessRoutes.forEach((item) => {
          //   router.addRoute(item)
          // })

          // 由于分模块顶级navbar(登录成功，获取信息permissions返回后设置顶级菜单)
          let accessRoutes = await store.dispatch('routes/setNavigateMenus')
          accessRoutes.forEach((item) => {
            router.addRoute(item)
          })
          next({ ...to, replace: true })
        } catch {
          await store.dispatch('user/resetAccessToken')
          if (progressBar) VabProgress.done()
        }
      }
    }
  } else {
    if (routesWhiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      if (recordRoute) {
        next(`/login?redirect=${to.path}`)
      } else {
        next('/login')
      }
      if (progressBar) VabProgress.done()
    }
  }
  document.title = getPageTitle(to.meta.title)
})
router.beforeEach(async (to, from, next) => {
  await store.dispatch('routes/setPageLoadingState', true)
  // 不做路由拦截啊,路由都由后台权限控制给了
  next()

  // 此处检查permission，不能访问则进去401
  // console.log('路由拦截', routesGuardWhiteList.indexOf(to.path));
  // if (routesGuardWhiteList.indexOf(to.path) !== -1) {
  //   next()
  // } else {
  //   // console.log('检查permissions');
  //   if (checkPermission(to.meta.permissions)) {
  //     next()
  //   } else {
  //     next({ replace: true, name: '401' })
  //   }
  // }
})
router.afterEach(() => {
  if (progressBar) VabProgress.done()
  store.dispatch('routes/setPageLoadingState', false)
})
